//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：gesturePassword.js
// 创建时间：2016年10月30日
// 创建人员：Panda
// 功能说明：手势密码登录压面
//################################

'use strict';

import React, {Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    Dimensions,
    TouchableOpacity,
    Image,
    InteractionManager,
    // Switch,
    Alert,
} from 'react-native';

import {
    CommonFunc,
    CommonData,
    UIConstants,
    Routes,
    PubSubTopics,
    Colors,
} from '../../common';

import PandaGesturePassword from '../../components/pandaGesturePassword';
import Button from '../../components/button';
import Images from '../../images';

import {loginWithUsernamePassword, clearLoginFailedMsg, clearActionType} from '../../actions';
import * as ActionTypes from '../../actions/types';

import NavigatorLevel1 from '../../main/pages/navigatorLevel1';
import PubSub from 'pubsub-js';

import LoginContainer from '../containers/loginContainer';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class GesturePassword extends Component {
    constructor(props) {
        super(props);

        this._renderDescription = this._renderDescriptionFunc.bind(this);
        this._renderActions = this._renderActionsFunc.bind(this);
        this._onFinish = this._onFinishFunc.bind(this);
        this._onReset = this._onResetFunc.bind(this);

        this.onAvatarContainerLayout = this.onAvatarContainerLayoutFunc.bind(this);
        this.onButtonTextPress = this.onButtonTextPressFunc.bind(this);

        this.user = props.route.data.user;

        this.state = {
            tips: UIConstants.login.inputGesturePassword,
            pandaPaddingTop: 240,
            tipsMarginTop: 160,
            buttonMarginTop: WINDOW_HEIGHT - 100,
        };
    }

    componentWillReceiveProps(nextProps) {
        switch (nextProps.actionType) {
            case ActionTypes.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_SUCCESS:
                this.loginSuccess(nextProps);
                break;
            case ActionTypes.LOGIN_LOGINWITHUSERNAMEPASSWORD_LOGIN_FALIED:
                this.loginFailed(nextProps);
                this.props.dispatch(clearActionType());
                break;
            default:
                break;
        }
    }

    loginSuccess(nextProps) {
        CommonData.userId = nextProps.userId;
        CommonData.notesId = nextProps.notesId;
        CommonData.soiHubIp = nextProps.soiHubIp;
        CommonData.ssoName = nextProps.ssoName;
        CommonData.pwdExpireTime = nextProps.pwdExpireTime;

        let isZxsoiMount = false;
        if (nextProps.soiHubIp && nextProps.soiHubIp.length > 0) {
            isZxsoiMount = true;
        }

        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);

        setTimeout(() => {
            // 跳转到主页面
            nextProps.navigatorRoot.resetTo({
                name: Routes.MAIN_NAVIGATOR,
                component: NavigatorLevel1,
                data: {
                    isZxsoiMount: isZxsoiMount,
                },
            });

            // 跳转到codepush页面
            // nextProps.navigatorRoot.resetTo({
            //     name: Routes.CODEPUSH,
            //     component: CodePushContainer,
            //     data: {
            //         isZxsoiMount: isZxsoiMount,
            //     },
            // });
        }, 500);
    }

    loginFailed(nextProps) {
        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);

        if (nextProps.code && nextProps.code !== 0) {
            if (nextProps.code === UIConstants.errorCodes.pwdExpired) {
                Alert.alert(
                    '提示',
                    '登录密码已过期，请切换到用户名密码登录！',
                    [
                        {
                            text: '确定',
                            onPress: () => {
                                const {dispatch} = this.props;
                                dispatch(clearActionType());
                                const {navigatorRoot} = this.props;
                                navigatorRoot.resetTo({
                                    name: Routes.LOGIN,
                                    component: LoginContainer,
                                    data: {
                                        isJumpFromGesturePasswordPage: true,
                                    },
                                });
                            }
                        },
                    ]
                );
            }
        }
        else {
            Alert.alert('提示', UIConstants.login.login_failed_tips + nextProps.loginFailedMsg, [{text: UIConstants.login.alert_confirm},]);
        }

        const {dispatch} = this.props;
        dispatch(clearLoginFailedMsg());

        this.setState({
            tips: UIConstants.login.inputGesturePassword,
        });
    }
    
    _renderThumbnails () {
        let thumbnails = []
        for (let i = 0; i < 9; i++) {
            let active = ~this.state.password.indexOf(i)
            thumbnails.push((
                <View
                    key={'thumb-' + i}
                    style={[
                        {width: 8, height: 8, margin: 2, borderRadius: 8, },
                        active ? {backgroundColor: '#00AAEF'} : {borderWidth: 1, borderColor: '#A9A9A9'}
                    ]}
                />
            ))
        }
        return (
            <View style={{width: 38, flexDirection: 'row', flexWrap: 'wrap'}}>
                {thumbnails}
            </View>
        )
    }

    _renderDescriptionFunc() {
        return (
            <View style={{height: 158, paddingBottom: 10, justifyContent: 'flex-end', alignItems: 'center',}}>
                {this._renderThumbnails()}
                <Text
                    style={{fontFamily: '.HelveticaNeueInterface-MediumP4', fontSize: 14, marginVertical: 6, color: this.state.messageColor}}>{this.state.message}</Text>
            </View>
        )
    }

    _renderActionsFunc() {
        return (
            <View
                style={{position: 'absolute', bottom: 0, flex:1, justifyContent: 'space-between', flexDirection: 'row', width: Dimensions.get('window').width, }}>
                <Button
                    style={{ margin: 10, height: 40, justifyContent: 'center', }}
                    textStyle={{fontSize: 14, color: '#A9A9A9'}}>
                    Forget password
                </Button>
                <Button
                    style={{ margin: 10, height: 40, justifyContent: 'center', }}
                    textStyle={{fontSize: 14, color: '#A9A9A9'}}>
                    Login other accounts
                </Button>
            </View>
        )
    }

    _onFinishFunc(password) {
        if (this.user && this.user.gesturePwd === password) {
            this.setState({
                tips: UIConstants.login.inputGesturePasswordSuccess,
                isWarning: false,
            });
            //登录
            PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.login.logining);
            const {dispatch} = this.props;
            dispatch(loginWithUsernamePassword(this.user.username, this.user.password));
        }
        else {
            //密码不对
            this.setState({
                tips: UIConstants.login.inputGesturePasswordFailed,
                isWarning: true,
            });

            setTimeout(() => {
                this.setState({
                    tips: UIConstants.login.inputGesturePassword,
                });
            }, 1500);
        }
    }

    _onResetFunc() {
        let isWarning = false;
        this.setState({
            isWarning,
        });
    }

    onAvatarContainerLayoutFunc() {
        this.avatarContainer && this.avatarContainer.measure((ox, oy, width, height, px, py) => {
            let paddingTop = py + height + 60;
            
            this.setState({
                pandaPaddingTop: paddingTop,
                tipsMarginTop: py + height - 30,
                buttonMarginTop: py + height + WINDOW_WIDTH - WINDOW_WIDTH / 4 + 60,
            });
        });
    }

    onButtonTextPressFunc() {
        const {navigatorRoot} = this.props;
        navigatorRoot.resetTo({
            name: Routes.LOGIN,
            component: LoginContainer,
            data: {
                isJumpFromGesturePasswordPage: true,
            },
        });
    }

    render () {
        return (
            <View style={styles.container}>
                <View style={styles.logo}>
                    <Image source={Images.Logo_abc} style={{width: WINDOW_WIDTH / 2,}} resizeMode={Image.resizeMode.contain} />
                </View>
                <View ref={(ref) => {this.avatarContainer = ref}} style={styles.avatarContainer} onLayout={this.onAvatarContainerLayout}>
                    <Image source={Images.Avatar_male} style={styles.avatar} resizeMode={Image.resizeMode.contain} />
                </View>
                <View style={{flex: 9}} />
                <View style={styles.gesturepasswordcontainer}>
                    <PandaGesturePassword
                        ref={(ref) => {this.pandaGesturePassword = ref}}
                        pointBackgroundColor={'#F4F4F4'}
                        isWarning={this.state.isWarning}
                        color={'#A9A9A9'}
                        activeColor={'#37B9D0'}
                        warningColor={'red'}
                        warningDuration={1500}
                        allowCross={true}
                        topComponent={this._renderDescription}
                        bottomComponent={this._renderActions}
                        onFinish={this._onFinish}
                        onReset={this._onReset}
                        pandaPaddingTop={this.state.pandaPaddingTop}
                    />
                </View>
                <View style={[styles.tips, {marginTop: this.state.tipsMarginTop}]}>
                    <View style={styles.innertipsview}>
                        <Text style={styles.tipstext}>
                            {this.state.tips}
                        </Text>
                    </View>
                </View>
                <View style={[styles.buttonview, {marginTop: this.state.buttonMarginTop}]}>
                    <Text style={styles.buttontext} onPress={this.onButtonTextPress}>{UIConstants.login.switchToUsernamePasswordLogin}</Text>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        height: WINDOW_HEIGHT,
        flexDirection: 'column',
        backgroundColor: Colors.appBackground,
    },
    logo: {
        flex: 1,
        alignItems: 'center',
    },
    avatarContainer: {
        flex: 3,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderTopWidth: 1,
        borderTopColor: Colors.gray,
        // borderBottomWidth: 1,
        // borderBottomColor: Colors.gray,
        marginTop: 20,
    },
    avatar: {
        alignSelf: 'center',
        alignItems: 'center',
        width: WINDOW_WIDTH / 4 * 1.3,
        height: WINDOW_WIDTH / 4 * 1.3,
        borderRadius: WINDOW_WIDTH / 12 * 1.3,
    },
    gesturepasswordcontainer: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        height: WINDOW_HEIGHT,
        top: 0,
        left: 0,
        alignItems: 'center',
        justifyContent: 'center',
        // backgroundColor: '#FFFFFF80',
        // marginTop: 200,
        // borderWidth: 4,
        // borderColor: 'blue',
    },
    tips: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        height: 100,
        top: 0,
        left: 0,
        // marginTop: 140,
        alignItems: 'center',
        justifyContent: 'center',
        // borderWidth: 5,
        // borderColor: 'red',
    },
    innertipsview: {
        alignSelf: 'center',
        alignItems: 'center',
        justifyContent: 'center',
    },
    tipstext: {
        fontSize: 26,
        color: 'black',
    },
    buttonview: {
        position: 'absolute',
        top: 0,
        width: WINDOW_WIDTH,
        height: 60,
        // backgroundColor: 'yellow',
        justifyContent: 'flex-end',
    },
    buttontext: {
        alignSelf: 'center', 
        fontSize: 18, 
        textDecorationLine: 'underline'
    },
});

export default GesturePassword